// web/src/app/learn/(dashboard)/(routes)/teacher/courses/[courseId]/_components/chapters-form.tsx
'use client';
import React, {useState} from 'react';
import {Course, Chapter} from "@prisma/client";
import * as z from "zod";
import {useRouter} from "next/navigation";
import {useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import toast from "react-hot-toast";
import {Button} from "@/components/ui/button";
import {Loader2, Pencil, PlusCircle} from "lucide-react";
import {cn} from "@/lib/utils";
import {Form, FormControl, FormField, FormItem, FormMessage} from "@/components/ui/form";
import {Textarea} from "@/components/ui/textarea";
import {Input} from "@/components/ui/input";
import ChaptersList from "@/app/learn/(dashboard)/(routes)/teacher/courses/[courseId]/_components/chapters-list";

interface Props {
    initialData: Course & {
        chapters: Chapter[]
    }
    courseId: string
}

const formSchema = z.object({
    title: z.string().min(1)
})

const ChaptersForm = ({initialData, courseId}: Props) => {
    const router = useRouter()

    const [isCreating, setIsCreating] = useState(false)
    const [isUpdating, setIsUpdating] = useState(false)
    const toggleCreating = () => setIsCreating((current) => !current)
    // const toggleUpdating = () => setIsUpdating((current) => !current)

    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            title: ''
        }
    })

    const {isSubmitting, isValid} = form.formState

    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        try {
            const res = await fetch(`/api/course/${courseId}/chapters`, {
                method: "POST",
                body: JSON.stringify(values),
                headers: {
                    "Content-Type": "application/json"
                }
            })
            if (!res.ok) throw new Error(`failed fetch`)
            toast.success(`创建成功`)
            toggleCreating()
            router.refresh()
        } catch (err) {
            toast.error(`Something went wrong`)
            console.error('Something went wrong', err);
        }
    }

    const onReorder = async (updateData: { id: string; position: number }[]) => {
        try {
            setIsUpdating(true)

            const res = await fetch(`/api/course/${courseId}/chapters/reorder`, {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    list: updateData
                })
            })
            if (!res.ok) throw new Error(`failed fetch`)
            toast.success("Chapter reordered")
            router.refresh()
        } catch (e) {
            toast.error(`Something went wrong`)
        } finally {
            setIsUpdating(false)
        }
    }

    const onEdit = (id: string) => {
        router.push(`/learn/teacher/courses/${courseId}/chapters/${id}`)
    }

    return (
        <div className={`relative mt-6 border bg-slate-100 rounded-md p-4`}>
            {isUpdating && (
                <div className={`absolute size-full bg-slate-500/20 top-0 right-0 rounded-md flex
                items-center justify-center`}>
                    <Loader2 className={`animate-spin size-6 text-sky-700`}/>
                </div>
            )}
            <div className={`font-medium flex items-center justify-between`}>
                Course chapters
                <Button variant={'ghost'}
                        onClick={toggleCreating}>
                    {isCreating ? (
                        <>Cancel</>
                    ) : (
                        <>
                            <PlusCircle className={`size-4 mr-2`}/>
                            Add a chapter
                        </>
                    )}
                </Button>
            </div>
            {isCreating && (
                <Form {...form}>
                    <form
                        onSubmit={form.handleSubmit(onSubmit)}
                        className={`space-y-4 mt-4`}
                    >
                        <FormField
                            control={form.control}
                            name={'title'}
                            render={({field}) => (
                                <FormItem>
                                    <FormControl>
                                        <Input
                                            placeholder={`e.g. 'Introduction to the course'`}
                                            disabled={isSubmitting}
                                            {...field}
                                        />
                                    </FormControl>
                                    <FormMessage/>
                                </FormItem>
                            )}
                        />
                        <Button
                            disabled={!isValid || isSubmitting}
                            type={'submit'}
                        >
                            Create
                        </Button>
                    </form>
                </Form>
            )}
            {!isCreating && (
                <div className={cn(
                    'text-sm mt-2',
                    !initialData.chapters.length && `text-slate-500 italic`
                )}>
                    {!initialData.chapters.length && 'No chapters'}
                    <ChaptersList
                        onEdit={onEdit}
                        onReorder={onReorder}
                        items={initialData.chapters || []}
                    />
                </div>
            )}
            {!isCreating && (
                <p className={`text-xs text-muted-foreground mt-4`}>
                    Drag and drop to reorder the chapters
                </p>
            )}
        </div>
    );
};

export default ChaptersForm;